import { ConfigProvider, message, Select } from "antd";
import { LaneMonitoringBox } from "./style";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { basicIp, wsIp } from "../../api/http";
import GljSt from "./newcomponents/GljSt";
import GljNd from "./newcomponents/GljNd";
import CenterVideo, { IChildRef } from "./newcomponents/CenterVideo";
import dayjs from "dayjs";
import { useLocation } from "react-router-dom";
import Pengbujiance from "./newcomponents/Pengbujiance";
import { IYckzZyLoadControlWareHouseList } from "../../type/remoteControl/loadingControlList";
import { getYckzZyLoadControlHetGlj, getYckzZyLoadControlWareHouseList, IYckzZyLoadControlHetGlj } from "../RemoteControl/api";
import { INoFenye } from "../../type/commit";
import { ISelectList } from "../../type/antd";
import { laneNumber } from "../../assets/data";
import { handleGetDictionaryItemValue } from "../../assets/fun/DictionaryItem";

type SKeys = `s${"0" | "1" | "2" | "3" | "4" | "5" | "6"}${| "1"
  | "2"
  | "3"
  | "4"
  | "5"
  | "6"
  | "7"
  | "8"
  | "9"
  | "0"}`;

export type MyObject = {
  [key in SKeys]?: boolean | string | null | number;
} & {
  url: string;
  carNo: string;
};

const LaneMonitoring = () => {
  const location = useLocation();
  const ws = useRef<WebSocket | null>(null); //ws连接
    const [geiliaojiData, setGeiliaojiData] = useState<IYckzZyLoadControlHetGlj>(); // 给料机数据

    const geiliaojiFun = useCallback(async () => {
        if (location.state && location.state.id) {
            const { code, msg, data } = await getYckzZyLoadControlHetGlj({ id: location.state?.id }) as { code: number; msg: string; data: IYckzZyLoadControlHetGlj };
            if (code === 20000) {
                setGeiliaojiData(data);
            } else {
                message.error(msg);
            }
        }

    }, [location.state])
    useEffect(() => {
      geiliaojiFun()
    
      return () => {
        
      }
    }, [geiliaojiFun])
    
  const childRefCenterVideo = useRef<IChildRef>(null); // 中间视频ref

  const [xingqiValue, setXingqiValue] = useState<number>(0); //星期
  const [riqiValue, setRiqiValue] = useState<string>(); //日期
  const [timeValue, setTime] = useState<string>(); // 时间

  const [fullShow, setFullShow] = useState(false);
  const [weightinfo, setWeightinfo] = useState<any>();
  const [wsData, setWsData] = useState<MyObject>();

  const [pengbujianceShow, setPengbujianceShow] = useState(false); // 篷布监测

  const [listData, setListData] = useState<IYckzZyLoadControlWareHouseList[]>(
    []
  ); // 列表数据
  const [listDataSelect, setListDataSelect] = useState<ISelectList[]>([]); // 列表数据选择
  const [chedaoId, setChedaoId] = useState<string>(); // 选择的装车站id
  const chedaohao = useMemo(() => {
    let channelNo = "--";
    listData.forEach((element) => {
      console.log(element.id)
      console.log(chedaoId)
      if (element.id === chedaoId) {
        channelNo = element.channelNo ? element.channelNo : "--";
      }
    });
    return channelNo;
  }, [chedaoId, listData]);
  const listFun = useCallback(async () => {
    const { code, msg, data } =
      (await getYckzZyLoadControlWareHouseList()) as INoFenye<IYckzZyLoadControlWareHouseList>;
    if (code === 20000) {
      data.forEach(element => {
        element.id = element.id.toString();
      });
      setListData(data);
      setListDataSelect(
        data.map((item) => ({
          label: item.loadStationName,
          value:  item.id.toString(),
        }))
      );
    } else {
      message.error(msg);
    }
  }, []);

  useEffect(() => {
    listFun();
  }, [listFun]);
  useEffect(() => {
    let idKsh = sessionStorage.getItem('idKsh');
    console.log(idKsh)
    if (idKsh) {
      setChedaoId(idKsh);
    }
    // if (location.state) {
    //   setChedaoId(location.state.id);
    // }
    return () => { };
  }, [location.state]);

  //建立ws连接
  const wsFun = useCallback(() => {

    if (chedaoId) {
          let reconnectInterval = 1000; // 重连间隔时间，单位毫秒
    let maxReconnectAttempts = 5; // 最大重连次数
    let reconnectAttempts = 0;
      let url = wsIp + `/websocket/KSHWebSocket?id=${chedaoId}`;
      ws.current = new WebSocket(url);
      ws.current.onopen = (e) => {
        message.success("ws连接成功");
        reconnectAttempts = 0; // 重置重连次数
      };
      childRefCenterVideo.current?.getZhuangtaiFun();
      ws.current.onmessage = (e) => {
        let data = JSON.parse(e.data);
        if (data.url) {
          data.url = basicIp + data.url;
          setPengbujianceShow(true);
        }
        setWsData((prevData) => {
          // 将新的数据合并到当前状态中
          return { ...prevData, ...data };
        });
      };
      ws.current.onclose = () => {
        console.log("ws连接断开");
        if (reconnectAttempts < maxReconnectAttempts) {
          setTimeout(() => {
            console.log('重新链接...');
            reconnectAttempts++;
            ws.current = new WebSocket(url); // 重新创建 WebSocket 实例
          }, reconnectInterval);
        } else {
          console.log('超过最大连接数');
        }
      };
    }

  }, [chedaoId]);
  //离开页面断开ws
  useEffect(() => {
    wsFun();
    return () => {
      ws.current?.close();
    };
  }, [wsFun]);
  useEffect(() => {

    let shuaxin = setInterval(() => {
      window.location.reload();
    }, 1000 * 60 * 60);
    return () => {
      clearInterval(shuaxin);
    }
  }, [])

  

  const handleCallBack = (bool: boolean, value: string, value2: string) => {
    setFullShow(bool);
    setWeightinfo({
      value: value,
      value2: value2,
    });
  };

  useEffect(() => {
    const timer = setInterval(() => {
      setTime(dayjs().format("HH:mm"));
      setXingqiValue(dayjs().day());
      setRiqiValue(dayjs().format("YYYY-MM-DD"));
    }, 1000);
    return () => {
      clearInterval(timer);
    };
  }, []);

  // 料场切换
  const handleLiaocangChange = (value: string) => {
    setChedaoId(value);
    sessionStorage.setItem('idKsh', value);
    // 重新链接ws
    if (ws.current) {
      console.log("可以关闭ws");
    }
    ws.current?.close();

    wsFun();
  };
  return (
    <LaneMonitoringBox style={{userSelect: "none"}}>
      {/* 顶端title */}
      <div className="top-title">
        <div
          className="left_zhuangtai"
        //
        >
          料仓切换：
          <ConfigProvider
            theme={{
              // components: useAntdSize(),
              components: {
                Select: {
                  optionSelectedBg: "#16426B",
                  optionSelectedColor: "#4AACFF",
                  selectorBg: "#042646",
                  activeBorderColor: "#1680D2",
                  colorBorder: "#074270",
                  colorText: "#3C87C6",
                  colorTextPlaceholder: "#3C87C6",
                  colorIconHover: "#3C87C6",
                  colorBgElevated: "#042646",
                },
              },
              token: {
                borderRadius: 4,
                fontSize: 14,
                controlHeight: 32,
                zIndexPopupBase: 9999,
                colorTextDescription: "#476C8D;",
              },
            }}
          >
            <Select
              value={chedaoId}
              style={{ width: "12rem", marginRight: "2rem" }}
              onChange={handleLiaocangChange}
              options={listDataSelect}
            />
          </ConfigProvider>
          {/* <Switch
            checkedChildren="自动"
            unCheckedChildren="手动"
            checked={loadingStatus === 0}
            onChange={handleSwitch}
            loading={loading}
          /> */}
          {handleGetDictionaryItemValue(laneNumber, chedaohao)}
          {/* <div
            className="btn"
            onClick={async () => {

              const {code, msg} = await getKshHandLift({id: location.state.id}) as {code: number; msg: string};
              if(code === 20000) {
                message.success('手动抬杆成功')
              }else{
                message.error(msg)
              }
            }}
            // onMouseDown={() => handleKongqipaoClick("2#", true)}
            // onMouseUp={() => handleKongqipaoClick("2#", false)}
          >
            手动抬杆
          </div> */}
        </div>

        <span className="text-title">骆驼山洗煤厂智能装车站可视化大屏</span>
        <div className="right-time">
          <span className="text-riqi">{riqiValue}</span>
          <span className="text-xingqi">周{xingqiValue}</span>
          <span className="text-xingqi">{timeValue}</span>
        </div>
      </div>
      <div className="neirong">
        {/* 左边1#给料机 */}
        <GljSt
          wsData={wsData}
          handleCallBack={handleCallBack}
          liaocangId={chedaoId}
          geiliaojiData={geiliaojiData}
        />
        {/* 中间 */}
        <CenterVideo
          ref={childRefCenterVideo}
          wsData={wsData}
          liaocangId={chedaoId}
          chedaohao={chedaohao}
        />
        {/* 右边2#给料机 */}
        <GljNd
          wsData={wsData}
          handleCallBack={handleCallBack}
          liaocangId={chedaoId}
          geiliaojiData={geiliaojiData}
        />
        {fullShow && (
          <div
            className="fullScreen"
            onClick={() => {
              setFullShow(false);
            }}
          >
            <div className="title">
              <span className="instant">瞬时量</span>
              <span className="accumulated">累积量</span>
            </div>
            <div className="values">
              <span className="instant-value">
                {weightinfo?.value}
                <span style={{ fontSize: "4rem", marginLeft: "1rem" }}>吨</span>
              </span>
              <span className="accumulated-value">
                {weightinfo?.value2}
                <span style={{ fontSize: "4rem", marginLeft: "1rem" }}>吨</span>
              </span>
            </div>
          </div>
        )}
      </div>
      <Pengbujiance
        open={pengbujianceShow}
        wsData={wsData}
        onCancel={() => {
          setPengbujianceShow(false);
        }}
      ></Pengbujiance>
    </LaneMonitoringBox>
  );
};

export default LaneMonitoring;
